package finance

import static groovyx.net.http.ContentType.HTML

class DowJonesService {

    static transactional = true

    def retrieve() {
//        def url = "http://www.djindexes.com/mdsidx/?event=components&symbol=DJI"
        def url = "http://www.djindexes.com"
        
        withAsyncHttp(poolSize : 4, uri : url, contentType : HTML) { 
            def result = get(path:'/mdsidx/', query: [event: 'components', symbol: 'DJI']) {
               resp, html ->  println ' got async response!'
               return html
            }
   
            assert result instanceof java.util.concurrent.Future
   
            while (! result.done) {
               Thread.sleep(2000)
            }
   
            def html = result.get().toString()
            
            for(line in html.split('\n')) {
                if(!line.startsWith('COMPANY NAME')) {
                   def fields = line.split('\t')
                   def name = fields[0]
                   def symbol = fields[2]
                   def weight = Double.valueOf(fields[6]) / 100
                   def instrument = saveInstrument(name, symbol)
                   new Index(name : 'Dow Jones Industrial Average', symbol: 'DJIA',
                       instrument : instrument, weight : weight).save()
                }
             }
        }
    }
    
    def saveInstrument(name, symbol) {
        def type = InstrumentType.findByType('Stock')
        def nasdaq = Datasource.findByName('NASDAQ')
        
        return new Instrument(name: name, symbol: symbol, 
            source: nasdaq, instrumentType : type).save()
    }
}